package com.esaheki.flashcards.ui;

import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.TableColumnModel;

import java.awt.*;
import java.awt.event.*;

import org.jdesktop.layout.GroupLayout;
import org.jdesktop.layout.LayoutStyle;

import com.esaheki.flashcards.classes.*;
import com.esaheki.flashcards.dao.*;
import com.esaheki.flashcards.supportModel.*;
import com.esaheki.flashcards.uiSupport.*;

/**
 *
 * @author esaheki
 */
public class MainPanel extends JFrame {
    /**
	 * 
	 */
	private static final long serialVersionUID = -8221322036722763437L;
	
    private JSplitPane splitPane;


    private static JPanel treePanel;
    private JScrollPane scrollPaneTree;
    private static JTree catTree;
    private JPanel infoPanel;
    private JLabel infoNameLabel;
    private JLabel infoScoreLabel;
    private static JLabel infoNameLabel2;
    private static JLabel infoScoreLabel2;
    private JButton btAddCat;
    private JButton btRemoveCat;
    private JButton btEditCat;
    private JButton btInfo;
    private JToolBar catToolBar;
    
    private JPanel rightSplitPanel;
    private JTabbedPane tabbedPane;
    
    private JScrollPane scrollPaneTable;
    private static JTable cardsTable;
    private JButton btAddCard;
    private JButton btRemoveCard;
    private JButton btEditCard;
    private JToolBar cardToolBar;
    
    private JPanel testPanel;
    private static int fontSize;
    private static JLabel frontLabel;
    private static JLabel backLabel;
    private JSeparator jSeparator1;
    private JSeparator jSeparator2;
    private static JButton answerButton;
    private static JButton rightButton;
    private static JButton wrongButton;
    
    private Icon addIcon;
    private Icon removeIcon;
    private Icon editIcon;
    private Icon infoIcon;
    
    private static Card currentCard;
    private static int currentPanelWidth;
    private static int currentPanelHeight;
    private static int lastSelectedTreeRow = 0;
    
    private static final String FONT_NAME = "Calisto MT";
	
	/** Creates new form NewJFrame2 
	 * @throws SQLException 
	 * @throws ClassNotFoundException */
    public MainPanel() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     * @throws SQLException 
     * @throws ClassNotFoundException 
     */
	private void initComponents() {

        splitPane = new JSplitPane();
        
        treePanel = new JPanel();
        scrollPaneTree = new JScrollPane();
        
        infoPanel = new JPanel();
        infoNameLabel = new JLabel();
        infoScoreLabel = new JLabel();
        infoNameLabel2 = new JLabel();
        infoScoreLabel2 = new JLabel();
        
        catToolBar = new JToolBar();
        btAddCat = new JButton();
        btRemoveCat = new JButton();
        btEditCat = new JButton();
        btInfo = new JButton();
        
        rightSplitPanel = new JPanel();
        tabbedPane = new JTabbedPane();
        scrollPaneTable = new JScrollPane();
        
        testPanel = new JPanel();
        
        cardToolBar = new JToolBar();
        btAddCard = new JButton();
        btRemoveCard = new JButton();
        btEditCard = new JButton();
        
        answerButton = new JButton();
        wrongButton = new JButton();
        rightButton = new JButton();
        jSeparator2 = new JSeparator();
        backLabel = new JLabel();
        jSeparator1 = new JSeparator();
        frontLabel = new JLabel();
        
        addIcon = new ImageIcon(getClass().getResource("images/add.png"));
        removeIcon = new ImageIcon(getClass().getResource("images/remove.png"));
        editIcon = new ImageIcon(getClass().getResource("images/edit.png"));
        infoIcon = new ImageIcon(getClass().getResource("images/info.png"));

        
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N
        setTitle("FlashCards");

        splitPane.setBorder(BorderFactory.createTitledBorder(""));
        splitPane.setName("splitPane"); // NOI18N



        treePanel.setName("treePanel"); // NOI18N

        catToolBar.setRollover(true);
        catToolBar.setName("catToolBar"); // NOI18N

        btAddCat.setIcon(addIcon); // NOI18N
        btAddCat.setFocusable(false);
        btAddCat.setHorizontalTextPosition(0);
        btAddCat.setMaximumSize(new Dimension(29, 28));
        btAddCat.setMinimumSize(new Dimension(29, 28));
        btAddCat.setName("btAddCat"); // NOI18N
        btAddCat.setVerticalTextPosition(3);
        btAddCat.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btAddCatActionPerformed(evt);
            }
        });
        catToolBar.add(btAddCat);

        btRemoveCat.setIcon(removeIcon); // NOI18N
        btRemoveCat.setFocusable(false);
        btRemoveCat.setHorizontalTextPosition(0);
        btRemoveCat.setMaximumSize(new Dimension(29, 28));
        btRemoveCat.setMinimumSize(new Dimension(29, 28));
        btRemoveCat.setName("btRemoveCat"); // NOI18N
        btRemoveCat.setVerticalTextPosition(3);
        btRemoveCat.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btRemoveCatActionPerformed(evt);
            }
        });
        catToolBar.add(btRemoveCat);
 
        btEditCat.setIcon(editIcon); // NOI18N
        btEditCat.setFocusable(false);
        btEditCat.setHorizontalTextPosition(0);
        btEditCat.setMaximumSize(new Dimension(29, 28));
        btEditCat.setMinimumSize(new Dimension(29, 28));
        btEditCat.setName("btEditCat"); // NOI18N
        btEditCat.setVerticalTextPosition(3);
        btEditCat.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btEditCatActionPerformed(evt);
            }
        });
        catToolBar.add(btEditCat);
        
        btInfo.setIcon(infoIcon); // NOI18N
        btInfo.setFocusable(false);
        btInfo.setHorizontalTextPosition(0);
        btInfo.setMaximumSize(new Dimension(29, 28));
        btInfo.setMinimumSize(new Dimension(29, 28));
        btInfo.setName("btInfo"); // NOI18N
        btInfo.setVerticalTextPosition(3);
        btInfo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btInfoActionPerformed(evt);
            }
        });
        catToolBar.add(btInfo);

        scrollPaneTree.setName("scrollPaneTree"); // NOI18N
        
		UserTreeModel treeModel = new UserTreeModel(new UserTree().getUserTree());
		
		catTree = new JTree(treeModel);
		catTree.setRowHeight(25);
		catTree.setSelectionRow(1);
		catTree.addTreeSelectionListener(new TreeListener());
		for (int i = 0; i < catTree.getRowCount(); i++) {
	         catTree.expandRow(i);
		}
          
        scrollPaneTree.setViewportView(catTree);
        
        
        
        infoPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        infoNameLabel.setText("Name:"); // NOI18N
        infoNameLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
        infoScoreLabel.setText("Average Score:"); // NOI18N
        infoScoreLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 10));

        infoNameLabel2.setText(""); // NOI18N
        infoNameLabel2.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
        infoScoreLabel2.setText(""); // NOI18N
        infoScoreLabel2.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
        refreshInfoPanel();

        GroupLayout infoPanelLayout = new GroupLayout(infoPanel);
        infoPanel.setLayout(infoPanelLayout);
        infoPanelLayout.setHorizontalGroup(
            infoPanelLayout.createParallelGroup(GroupLayout.LEADING)
            .add(infoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(infoPanelLayout.createParallelGroup(GroupLayout.LEADING)
                    .add(infoPanelLayout.createSequentialGroup()
                        .add(infoNameLabel)
                        .addPreferredGap(LayoutStyle.RELATED, 68, Short.MAX_VALUE)
                        .add(infoNameLabel2))
                    .add(infoPanelLayout.createSequentialGroup()
                        .add(infoScoreLabel)
                        .addPreferredGap(LayoutStyle.RELATED, 32, Short.MAX_VALUE)
                        .add(infoScoreLabel2)))
                .addContainerGap())
        );
        infoPanelLayout.setVerticalGroup(
            infoPanelLayout.createParallelGroup(GroupLayout.LEADING)
            .add(infoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(infoPanelLayout.createParallelGroup(GroupLayout.BASELINE)
                    .add(infoNameLabel)
                    .add(infoNameLabel2))
                .addPreferredGap(LayoutStyle.RELATED)
                .add(infoPanelLayout.createParallelGroup(GroupLayout.BASELINE)
                    .add(infoScoreLabel)
                    .add(infoScoreLabel2))
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );


        GroupLayout treePanelLayout = new GroupLayout(treePanel);
        treePanel.setLayout(treePanelLayout);
        treePanelLayout.setHorizontalGroup(
            treePanelLayout.createParallelGroup(GroupLayout.LEADING)
            .add(infoPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(catToolBar, GroupLayout.PREFERRED_SIZE, 220, Short.MAX_VALUE)
            .add(scrollPaneTree, GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
        );
        treePanelLayout.setVerticalGroup(
            treePanelLayout.createParallelGroup(GroupLayout.LEADING)
            .add(treePanelLayout.createSequentialGroup()
            	.add(scrollPaneTree, GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE)
            	.addPreferredGap(LayoutStyle.RELATED)
            	.add(infoPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.RELATED)
                .add(10,10,10)
                .add(catToolBar, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE))
        );

        splitPane.setLeftComponent(treePanel);
        
        
        
        
        
        rightSplitPanel.setName("rightSplitPanel"); // NOI18N

        cardToolBar.setRollover(true);
        cardToolBar.setName("cardToolBar"); // NOI18N

        btAddCard.setIcon(addIcon);
        btAddCard.setFocusable(false);
        btAddCard.setHorizontalTextPosition(0);
        btAddCard.setMaximumSize(new Dimension(29, 28));
        btAddCard.setMinimumSize(new Dimension(29, 28));
        btAddCard.setName("btAddCard"); // NOI18N
        btAddCard.setVerticalTextPosition(3);
        btAddCard.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btAddCardActionPerformed(evt);
            }
        });
        cardToolBar.add(btAddCard);

        btRemoveCard.setIcon(removeIcon); // NOI18N
        btRemoveCard.setFocusable(false);
        btRemoveCard.setHorizontalTextPosition(0);
        btRemoveCard.setMaximumSize(new Dimension(29, 28));
        btRemoveCard.setMinimumSize(new Dimension(29, 28));
        btRemoveCard.setName("btRemoveCard"); // NOI18N
        btRemoveCard.setVerticalTextPosition(3);
        btRemoveCard.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btRemoveCardActionPerformed(evt);
            }
        });
        cardToolBar.add(btRemoveCard);
        
        btEditCard.setIcon(editIcon); // NOI18N
        btEditCard.setFocusable(false);
        btEditCard.setHorizontalTextPosition(0);
        btEditCard.setMaximumSize(new Dimension(29, 28));
        btEditCard.setMinimumSize(new Dimension(29, 28));
        btEditCard.setName("btEditCard"); // NOI18N
        btEditCard.setVerticalTextPosition(3);
        btEditCard.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btEditCardActionPerformed(evt);
            }
        });
        cardToolBar.add(btEditCard);

        tabbedPane.setName("tabbedPane"); // NOI18N
        tabbedPane.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent evt) {
                tabbedPaneCardStateChanged(evt);
            }
        });

        scrollPaneTable.setName("scrollPaneTable"); // NOI18N

        CardTableModel model = new CardTableModel(new CardList().getCardList());
        cardsTable = new JTable(model);

        cardsTable.setName("cardsTable"); // NOI18N
        cardsTable.setRowHeight(20);
        cardsTable.setAutoCreateRowSorter(true);
        cardsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        cardsTable.setSelectionBackground(new Color(56,117,215));
        refreshTable();
        
        scrollPaneTable.setViewportView(cardsTable);

        tabbedPane.addTab("Edit", scrollPaneTable); // NOI18N

        testPanel.setBackground(new Color(255,255,255)); // NOI18N
        testPanel.setName("testPanel"); // NOI18N

		currentCard = new Roulette().getCard();

        frontLabel.setFont(new Font(FONT_NAME, Font.PLAIN, 34)); // NOI18N
        frontLabel.setHorizontalAlignment(SwingConstants.CENTER);
        frontLabel.setText(currentCard.getFront()); // NOI18N
        frontLabel.setName("frontLabel"); // NOI18N
        frontLabel.addComponentListener(new ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                frontLabelComponentResized(evt);
            }
        });

        jSeparator1.setName("jSeparator1"); // NOI18N
        
        backLabel.setFont(new Font(FONT_NAME, Font.PLAIN, 24)); // NOI18N
        backLabel.setForeground(new Color(150,150,150));
        backLabel.setHorizontalAlignment(SwingConstants.CENTER);
        backLabel.setText(" "); // NOI18N
        backLabel.setName("backLabel"); // NOI18N
        
        refreshFontSize();

        jSeparator2.setName("jSeparator2"); // NOI18N
        
        answerButton.setText("Show Answer"); // NOI18N
        answerButton.setName("answerButton"); // NOI18N
        answerButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                answerButtonActionPerformed(evt);
            }
        });

        wrongButton.setText("Wrong"); // NOI18N
        wrongButton.setVisible(false);
        wrongButton.setName("wrongButton"); // NOI18N
        wrongButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                wrongButtonActionPerformed(evt);
            }
        });

        rightButton.setText("Right"); // NOI18N
        rightButton.setVisible(false);
        rightButton.setName("rightButton"); // NOI18N
        rightButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                rightButtonActionPerformed(evt);
            }
        });
        
        GroupLayout testPanelLayout = new GroupLayout(testPanel);
        testPanel.setLayout(testPanelLayout);
        testPanelLayout.setHorizontalGroup(
            testPanelLayout.createParallelGroup(GroupLayout.LEADING)
            .add(GroupLayout.TRAILING, testPanelLayout.createSequentialGroup()
                .add(testPanelLayout.createParallelGroup(GroupLayout.TRAILING)
                    .add(GroupLayout.LEADING, backLabel, GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)
                    .add(GroupLayout.LEADING, frontLabel, GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)
                    .add(GroupLayout.LEADING, jSeparator2, GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)
                    .add(GroupLayout.LEADING, jSeparator1, GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)
                    .add(GroupLayout.CENTER, testPanelLayout.createSequentialGroup()
                    	.addContainerGap()
                        .add(answerButton, GroupLayout.PREFERRED_SIZE, 185, GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(rightButton, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(LayoutStyle.RELATED)
                        .add(wrongButton, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE))
                    )
                )
        );
        testPanelLayout.setVerticalGroup(
            testPanelLayout.createParallelGroup(GroupLayout.LEADING)
            .add(GroupLayout.TRAILING, testPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(frontLabel, GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                .addPreferredGap(LayoutStyle.RELATED)
                .add(jSeparator1, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.RELATED)
                .add(backLabel, GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                .addPreferredGap(LayoutStyle.RELATED)
                .add(jSeparator2, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.UNRELATED)
                .add(testPanelLayout.createParallelGroup(GroupLayout.BASELINE)
                    .add(wrongButton)
                    .add(rightButton)
                    .add(answerButton))
                .addContainerGap())
        );
        
        tabbedPane.addTab("Test", testPanel); // NOI18N

        GroupLayout rightSplitPanelLayout = new GroupLayout(rightSplitPanel);
        rightSplitPanel.setLayout(rightSplitPanelLayout);
        rightSplitPanelLayout.setHorizontalGroup(
            rightSplitPanelLayout.createParallelGroup(GroupLayout.LEADING)
            .add(cardToolBar, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE)
            .add(tabbedPane, GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );
        rightSplitPanelLayout.setVerticalGroup(
            rightSplitPanelLayout.createParallelGroup(GroupLayout.LEADING)
            .add(rightSplitPanelLayout.createSequentialGroup()
            	.add(tabbedPane, GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
            	.addPreferredGap(LayoutStyle.RELATED)
                .add(cardToolBar, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE))
        );

        splitPane.setRightComponent(rightSplitPanel);
        
        infoPanel.setVisible(false);

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.LEADING)
            .add(splitPane, GroupLayout.DEFAULT_SIZE, 757, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.LEADING)
            .add(splitPane, GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE)
        );

        pack();
    }
    
	private void btAddCatActionPerformed(ActionEvent evt) { 

		String name = new String();
		int[] temp = catTree.getSelectionRows();
		lastSelectedTreeRow = temp[0];

		try {
			if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof Category) {
				Category cat = (Category)catTree.getSelectionPath().getLastPathComponent();
				new AddCardForm(cat).setVisible(true);
				return;
			}
			else if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof User) {
				User user = (User)catTree.getSelectionPath().getLastPathComponent();
				name = JOptionPane.showInputDialog(null,"Category Name:","Add New Category",JOptionPane.PLAIN_MESSAGE);
				Category cat = new Category();
				cat.setName(name);
				CategoryDAO cDao = new CategoryDAO();
				cDao.insertCategory(cat, user);
			}
			else if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof ArrayList<?>) {
				name = JOptionPane.showInputDialog(null,"User Name:","Add New User",JOptionPane.PLAIN_MESSAGE);
				User user = new User(name);		
				UserDAO uDao = new UserDAO();
				uDao.insertUser(user);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		refreshTree();
		
		/* Localiza e seleciona na JTree o item adicionado */
		int i;
		for (i = 0; i < catTree.getRowCount(); i++) {
			if (name.equals(catTree.getPathForRow(i).getLastPathComponent().toString()))
				break;
		}
		catTree.setSelectionRow(i);
    }
    
	private void btRemoveCatActionPerformed(ActionEvent evt) {
		if (catTree.isSelectionEmpty()) {
			JOptionPane.showMessageDialog(null, "Select an item first.");
			return;
		}
		int[] temp = catTree.getSelectionRows();
		lastSelectedTreeRow = temp[0] - 1;
		try {
			if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof Category) {
				Category cat = (Category)catTree.getSelectionPath().getLastPathComponent();
				int n = JOptionPane.showConfirmDialog(null,
						"Are you sure you want to remove category \""+ cat +"\"?",
						"Delete Category",
						JOptionPane.YES_NO_CANCEL_OPTION);
				if (n == 0) {
					CategoryDAO cDao = new CategoryDAO();
					cDao.deleteCategory(cat);
				}
			}
			else if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof User) {
				User user = (User)catTree.getSelectionPath().getLastPathComponent();
				int n = JOptionPane.showConfirmDialog(null,
						"Are you sure you want to remove user \""+ user +"\" and all containing cards?",
						"Delete Category",
						JOptionPane.YES_NO_CANCEL_OPTION);
				if (n == 0) {
					UserDAO uDao = new UserDAO();
					uDao.deleteUser(user);
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		refreshTree();
		catTree.setSelectionRow(lastSelectedTreeRow);
	}

	private void btEditCatActionPerformed(ActionEvent evt) { 
		if (catTree.isSelectionEmpty()) {
			JOptionPane.showMessageDialog(null, "Select an item first.");
			return;
		}
		int[] temp = catTree.getSelectionRows();
		lastSelectedTreeRow = temp[0];
		try {
			if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof Category) {
				Category cat = (Category)catTree.getSelectionPath().getLastPathComponent();
				String catname = JOptionPane.showInputDialog(null,"Category Name:","Edit Category Name",JOptionPane.PLAIN_MESSAGE);
				if (catname == null) return;
				cat.setName(catname);
				CategoryDAO cDao = new CategoryDAO();
				cDao.updateCategory(cat);
			}
			else if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof User) {
				User user = (User)catTree.getSelectionPath().getLastPathComponent();
				String username = JOptionPane.showInputDialog(null,"User Name:","Edit User Name",JOptionPane.PLAIN_MESSAGE);
				if (username == null) return;
				user.setName(username);
				UserDAO uDao = new UserDAO();
				uDao.updateUser(user);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		refreshTree();
		catTree.setSelectionRow(lastSelectedTreeRow);
	}
    
    private void btInfoActionPerformed(ActionEvent evt) {
    	if (infoPanel.isVisible())  infoPanel.setVisible(false);
    	else infoPanel.setVisible(true);
    }
    
    private void btAddCardActionPerformed(ActionEvent evt) {                                         
    	if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof Category) {
    		Category cat = (Category)catTree.getSelectionPath().getLastPathComponent();
    		new AddCardForm(cat).setVisible(true);
    	}
    }
    
    private void btRemoveCardActionPerformed(ActionEvent evt) {
    	if (!cardsTable.isFocusOwner()) {
    		JOptionPane.showMessageDialog(null, "Select a card first.");
    		return;
    	}
    	if ((Object)catTree.getLastSelectedPathComponent() instanceof Category) {
    		Card card = new Card();
    		card.setFront((String)cardsTable.getValueAt(cardsTable.getSelectedRow(), 0));
    		card.setBack((String)cardsTable.getValueAt(cardsTable.getSelectedRow(), 1));
    		try {
    			CardDAO cDao = new CardDAO();
    			card = cDao.getCompleteCard(card);
    			cDao.deleteCard(card);

    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		CardTableModel model = new CardTableModel(
    				new CardList((Object)catTree.getLastSelectedPathComponent()).getCardList());
			cardsTable.setModel(model);
    	}
    }
    
    private void btEditCardActionPerformed(ActionEvent evt) {  
    	if (!cardsTable.isFocusOwner()) {
    		JOptionPane.showMessageDialog(null, "Select a card first.");
    		return;
    	}
    	try {
    		Card card = new Card();
    		card.setFront((String)cardsTable.getValueAt(cardsTable.getSelectedRow(), 0));
    		card.setBack((String)cardsTable.getValueAt(cardsTable.getSelectedRow(), 1));

    		CardDAO cDao = new CardDAO();
    		card = cDao.getCompleteCard(card);
    		new EditCardForm(card).setVisible(true);
    	} catch (ClassNotFoundException e) {
    		e.printStackTrace();
    	} catch (SQLException e) {
    		e.printStackTrace();
    	}
    }
    
    private void answerButtonActionPerformed(ActionEvent evt) {
    	currentCard.setCountTests(currentCard.getCountTests() + 1);
    	backLabel.setText(currentCard.getBack());
    	answerButton.setVisible(false);
		rightButton.setVisible(true);
		wrongButton.setVisible(true);
    }
    
    private void rightButtonActionPerformed(ActionEvent evt) {
    	currentCard.setCountRight(currentCard.getCountRight() + 1);
    	
		try {
			CardDAO cDao = new CardDAO();
			cDao.updateCard(currentCard);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return;
		} catch (SQLException e) {
			e.printStackTrace();
			return;
		}
		updateScore();
		refreshCurrentCard();
    	refreshTestPanel();
    	refreshInfoPanel();
    	
    	int[] temp = catTree.getSelectionRows();
    	lastSelectedTreeRow = temp[0];
    	refreshTree();
    	catTree.setSelectionRow(lastSelectedTreeRow);
    }
    
    private void wrongButtonActionPerformed(ActionEvent evt) {
    	
    	try {
    		CardDAO cDao = new CardDAO();
			cDao.updateCard(currentCard);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return;
		} catch (SQLException e) {
			e.printStackTrace();
			return;
		}
		updateScore();
		refreshCurrentCard();
    	refreshTestPanel();
    	refreshInfoPanel();
    	
    	int[] temp = catTree.getSelectionRows();
    	lastSelectedTreeRow = temp[0];
    	refreshTree();
    	catTree.setSelectionRow(lastSelectedTreeRow);
    }
    
    private void tabbedPaneCardStateChanged(ChangeEvent evt) {
    	if (tabbedPane.getSelectedIndex() == 0) refreshTable();
    	else refreshTestPanel();
    }
    
    protected static class TreeListener implements TreeSelectionListener {

		@Override
		public void valueChanged(TreeSelectionEvent e) {
			refreshTable();
	    	refreshCurrentCard();
	    	refreshTestPanel();
	    	refreshInfoPanel();
		}
    }
	
    public static void refreshTable() {
    	if (catTree.isSelectionEmpty()) {
    		catTree.setSelectionRow(lastSelectedTreeRow);
    	}
    	CardTableModel model = new CardTableModel(
    			new CardList((Object)catTree.getSelectionPath().getLastPathComponent()).getCardList());
    	cardsTable.setModel(model);
    	
    	/* Renderiza a coluna de score no formato de porcentagem */
    	TableColumnModel tcm = cardsTable.getColumnModel();
    	NumberFormat formatter = NumberFormat.getPercentInstance();
    	FormatRenderer r = new FormatRenderer(formatter);
    	r.setHorizontalAlignment(SwingConstants.RIGHT);
    	tcm.getColumn(2).setCellRenderer(r);
    }

	private static void refreshTree() {
		UserTreeModel treeModel = new UserTreeModel(new UserTree().getUserTree());
		catTree.setModel(treeModel);
		for (int i = 0; i < catTree.getRowCount(); i++) {
	         catTree.expandRow(i);
		}
	}
	
	private static void refreshTestPanel() {
		if (currentCard == null) {
			frontLabel.setText(" ");
			backLabel.setText(" ");
			answerButton.setVisible(true);
			answerButton.setEnabled(false);
			rightButton.setVisible(false);
			wrongButton.setVisible(false);
		}
		else {
			frontLabel.setText(currentCard.getFront());
			backLabel.setText(" ");
			refreshFontSize();
			answerButton.setVisible(true);
			answerButton.setEnabled(true);
			rightButton.setVisible(false);
			wrongButton.setVisible(false);
		}
	}
	
	private static void refreshInfoPanel() {
		if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof Category) {
			Category cat = (Category)catTree.getSelectionPath().getLastPathComponent();
			infoNameLabel2.setText(cat.getName());
			NumberFormat formatter = NumberFormat.getPercentInstance();
			infoScoreLabel2.setText(formatter.format(cat.getAverageScore()));
    	}
    	else if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof User) {
    		User user = (User)catTree.getSelectionPath().getLastPathComponent();
			infoNameLabel2.setText(user.getName());
			NumberFormat formatter = NumberFormat.getPercentInstance();
			infoScoreLabel2.setText(formatter.format(user.getAverageScore()));
    	}
    	else if ((Object)catTree.getSelectionPath().getLastPathComponent() instanceof ArrayList<?>) {
			infoNameLabel2.setText("");
			infoScoreLabel2.setText("");
    	}
	}
	
	private static void refreshCurrentCard() {
		Roulette roulette = new Roulette((Object)catTree.getSelectionPath().getLastPathComponent());
		currentCard = roulette.getCard();
	}
	
    private void frontLabelComponentResized(java.awt.event.ComponentEvent evt) {
    	currentPanelWidth = this.getWidth();
    	currentPanelHeight = this.getHeight();
    	refreshFontSize();
    }
	
	private static void refreshFontSize() {
		if (currentCard == null) {
			return;
		}
		fontSize = (currentPanelWidth - treePanel.getWidth() + 40) / currentCard.getFront().length();
    	int temp = (currentPanelWidth - treePanel.getWidth() + 40) / currentCard.getBack().length();
    	if (temp < fontSize) {
    		fontSize = temp;
    	}
    	if (fontSize > ((currentPanelHeight - 116)/4.2)) {
    		fontSize = (int) ((currentPanelHeight - 116)/4.2);
    	}
    	frontLabel.setFont(new Font(FONT_NAME, Font.PLAIN, fontSize));
    	backLabel.setFont(new Font(FONT_NAME, Font.PLAIN, fontSize - 5));
	}
    
    private void updateScore() {
    	Statistic st = new Statistic();
    	st.updateScore();
    }
}
